#include <iostream>
#include <cassert>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <thread>
#include <chrono>
#include <assert.h>
#include "../src/http/server.h"
#include "../src/asset/manager.h"
#include "../src/utils/string.h"

using namespace std;
// using namespace common;

// 简单的HTTP客户端函数，用于测试
std::string httpRequest(const std::string &method, const std::string &path, const std::string &body = "")
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        return "";
    }

    struct sockaddr_in serv_addr;
    std::memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8080);

    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
    {
        close(sockfd);
        return "";
    }

    if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        close(sockfd);
        return "";
    }

    std::string request = method + " " + path + " HTTP/1.1\r\n";
    request += "Host: localhost:8080\r\n";
    request += "Connection: close\r\n";

    if (!body.empty())
    {
        request += "Content-Length: " + std::to_string(body.size()) + "\r\n";
        request += "Content-Type: application/json\r\n";
    }

    request += "\r\n";
    request += body;

    send(sockfd, request.c_str(), request.size(), 0);

    char buffer[4096];
    std::string response;
    ssize_t bytesRead;

    while ((bytesRead = read(sockfd, buffer, sizeof(buffer) - 1)) > 0)
    {
        buffer[bytesRead] = '\0';
        response += buffer;
    }

    close(sockfd);
    return response;
}

// 测试HTTP服务器
void testHttpServer()
{
    AssetManager manager;
    HttpServer server(8080, &manager);

    // 在单独的线程中启动服务器
    std::thread serverThread([&server]()
                             { server.start(); });

    // 等待服务器启动
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 测试初始状态下的资产列表
    std::string response = httpRequest("GET", "/assets");
    assert(StringUtils::startsWith(response, "HTTP/1.1 200 OK"));
    assert(StringUtils::contains(response, "[]")); // 应该是空数组

    // 测试创建资产
    std::string newAsset = "{\"name\":\"Test Server\",\"type\":\"IT Equipment\",\"value\":5000.0}";
    response = httpRequest("POST", "/assets", newAsset);
    assert(StringUtils::startsWith(response, "HTTP/1.1 201 Created"));
    assert(StringUtils::contains(response, "Test Server"));

    // 测试获取所有资产
    response = httpRequest("GET", "/assets");
    assert(StringUtils::startsWith(response, "HTTP/1.1 200 OK"));
    assert(StringUtils::contains(response, "Test Server"));

    // 测试获取单个资产
    response = httpRequest("GET", "/assets/1");
    assert(StringUtils::startsWith(response, "HTTP/1.1 200 OK"));
    assert(StringUtils::contains(response, "Test Server"));

    // 测试更新资产
    std::string updatedAsset = "{\"name\":\"Test Server Updated\",\"type\":\"IT Equipment\",\"value\":6000.0}";
    response = httpRequest("PUT", "/assets/1", updatedAsset);
    assert(StringUtils::startsWith(response, "HTTP/1.1 200 OK"));
    assert(StringUtils::contains(response, "Test Server Updated"));

    // 测试删除资产
    response = httpRequest("DELETE", "/assets/1");
    assert(StringUtils::startsWith(response, "HTTP/1.1 204 No Content"));

    // 测试删除后的资产是否存在
    response = httpRequest("GET", "/assets/1");
    assert(StringUtils::startsWith(response, "HTTP/1.1 404 Not Found"));

    // 测试不存在的路由
    response = httpRequest("GET", "/invalid/path");
    assert(StringUtils::startsWith(response, "HTTP/1.1 404 Not Found"));

    // 停止服务器
    server.stop();
    serverThread.join();

    std::cout << "All HTTP tests passed!" << std::endl;
}

int main()
{
    testHttpServer();
    return 0;
}
